package com.ztesoft.book.common.utils.exception;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 异常
 *
 * @author wanshuhan
 * @date 2020/9/9 11:32
 */
public final class ExUtil {
    private ExUtil() {

    }

    private static final Class<? extends RuntimeException> DEFAULT_CLASS = ServiceException.class;

    /**
     * 抛指定异常,没有就是ServiceException
     *
     * @param clazz        clazz
     * @param errorMessage errorMessage
     */
    public static void throwEx(String errorMessage, Class<? extends RuntimeException> clazz) {
        clazz = (clazz == null ? DEFAULT_CLASS : clazz);
        if (StrUtil.isNotEmpty(errorMessage)) {
            throw ReflectUtil.newInstance(clazz, errorMessage);
        }
        else {
            throw ReflectUtil.newInstance(clazz);
        }
    }

    /**
     * 抛ServiceException
     *
     * @param errorMessage errorMessage
     */
    public static void throwEx(String errorMessage) {
        throwEx(errorMessage, DEFAULT_CLASS);
    }

    /**
     * 检查参数
     *
     * @param expression expression
     */
    public static void checkArgument(boolean expression) {
        if (!expression) {
            throw ReflectUtil.newInstance(DEFAULT_CLASS);
        }
    }

    /**
     * 检查参数
     *
     * @param expression   expression
     * @param errorMessage errorMessage
     */
    public static void checkArgument(boolean expression, String errorMessage) {
        if (!expression) {
            throw ReflectUtil.newInstance(DEFAULT_CLASS, errorMessage);
        }
    }

    /**
     * 检查空指针
     *
     * @param reference reference
     * @param <T>       范型
     * @return t
     */
    public static <T> T checkNotNull(T reference) {
        if (reference == null) {
            throw ReflectUtil.newInstance(DEFAULT_CLASS, "空指针异常");
        }
        else {
            return reference;
        }
    }

    /**
     * 检查空指针
     *
     * @param reference    reference
     * @param errorMessage errorMessage
     * @param <T>          范型
     * @return t
     */
    public static <T> T checkNotNull(T reference, String errorMessage) {
        if (reference == null) {
            throw ReflectUtil.newInstance(DEFAULT_CLASS, errorMessage);
        }
        else {
            return reference;
        }
    }

    /**
     * 获取ServiceException里的报错信息
     *
     * @param e          异常
     * @param defaultMsg 默认信息
     * @return String
     */
    public static String getServiceExMsg(Exception e, String defaultMsg) {
        if (e instanceof ServiceException) {
            defaultMsg = e.getMessage();
        }
        return defaultMsg;
    }
}
